package com.jokul.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.lang3.StringUtils;

/**
 * @author jokul
 * @date 2013-3-27
 * @time 下午4:17:44
 */
@MultipartConfig
@WebServlet(urlPatterns = "/mail.do", initParams = {
		@WebInitParam(name = "mailHost", value = "smtp.gmail.com"),
		@WebInitParam(name = "mailPort", value = "465"),
		@WebInitParam(name = "username", value = "jokul2011@gmail.com"),
		@WebInitParam(name = "password", value = "jokul5658551") })
public class MailServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2346526475928996010L;

	private String mailHost;
	private String mailPort;
	private String username;
	private String password;
	private Properties properties;

	public void init() throws ServletException {
		mailHost = getServletConfig().getInitParameter("mailHost");
		mailPort = getServletConfig().getInitParameter("mailPort");
		username = getServletConfig().getInitParameter("username");
		password = getServletConfig().getInitParameter("password");

		properties = new Properties();
		properties.put("mail.smtp.host", mailHost);
		properties.setProperty("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		properties.setProperty("mail.smtp.socketFactory.fallback", "false");
		properties.setProperty("mail.smtp.port", mailPort);
		properties.setProperty("mail.smtp.socketFactory.port", mailPort);
		properties.setProperty("mail.smtp.auth", "true");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String from = request.getParameter("from");
		String to = request.getParameter("to");
		String subject = request.getParameter("subject");
		String text = request.getParameter("text");
		Part part = request.getPart("file");

		try {
			Message message = getMessage(from, to, subject, text, part);
			Transport.send(message);
			response.getWriter().println("发送成功！");
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}

	private Message getMessage(String from, String to, String subject,
			String text, Part part) throws AddressException, MessagingException, IOException {
		Session session = Session.getDefaultInstance(properties,
				new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);
		message.setSentDate(new Date());
		// message.setText(text);

		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setContent(text, "text/html; charset=UTF-8");
		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(mimeBodyPart);

		String fileName = getFileName(part);
		if(StringUtils.isNotEmpty(fileName)) {
			MimeBodyPart bodyPart = new MimeBodyPart();
			bodyPart.setFileName(MimeUtility.encodeText(fileName, "UTF-8", "B"));
			bodyPart.setContent(getBytes(part), part.getContentType());
			multipart.addBodyPart(bodyPart);
		}
		
		message.setContent(multipart);

		return message;
	}

	private String getFileName(Part part) {
		String header = part.getHeader("Content-Disposition");
		String fileName = header.substring(header.indexOf("filename=\""),
				header.lastIndexOf("\""));
		return fileName;
	}
	
	private byte[] getBytes(Part part) throws IOException {
		InputStream is = part.getInputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int length = -1;
		while((length = is.read(buffer)) != -1) {
			baos.write(buffer, 0, length);
		}
		is.close();
		baos.close();
		return baos.toByteArray();
	}
}
